﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Brc_PaaS.Common.Helper
{
    /// <summary>
    /// 定义泛型委托为setter
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    public delegate void SetValue<T>(T value);
    public static class ToModel<T> where T : class, new()
    {
        /// <summary>
        /// 创建SetValue委托
        /// </summary>
        /// <param name="model"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        private static Delegate CreateSetDelegate(T model, string propertyName)
        {
            var propertyInfo = model.GetType().GetProperty(propertyName);
            if (propertyInfo == null)
            {
                return null;
            }
            MethodInfo mi = propertyInfo.GetSetMethod();
            Type delType = typeof(SetValue<>).MakeGenericType(GetPropertyType(propertyName));
            return Delegate.CreateDelegate(delType, model, mi);
        }
        /// <summary>
        /// 获取类型
        /// </summary>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        private static Type GetPropertyType(string propertyName)
        {
            return typeof(T).GetProperty(propertyName).PropertyType;
        }
        /// <summary>
        /// 反射dynamic
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetDelegate_ToDynamicDic(dynamic model)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (model == null)
                return dic;
            var properties = model.GetType().GetProperties();
            foreach (var item in properties)
            {
                var value = item.GetValue(model);
                dic.Add(item.Name, value != null ? value.ToString() : string.Empty);
            }
            return dic;
        }
        public static Dictionary<string, string> GetDelegate_ToModelDic(T model)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (model == null)
                return dic;
            var properties = model.GetType().GetProperties();
            foreach (var item in properties)
            { 
                var value = item.GetValue(model);
                dic.Add(item.Name, value != null ? value.ToString() : string.Empty);
            }
            return dic;
        }

        /// <summary>
        /// 判断是否为空
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static bool IsNullOrDBNull(object obj)
        {
            return (obj == null || (obj is DBNull)) ? true : false;
        }
    }
}
